#!/usr/bin/perl
#decode.pl
#decodes lab1 files with a code table
#USAGE: perl decode.pl -list FILELIST -conv CONVERTTABLES [-lab1 INPUTFOLDER -h]

#Version: 1.1
#@autor: Igor Jauk

#Changelist:
#config class support
#code optimization
#optimized error handling
#flexible input folder choice


use FindBin qw($Bin);
use lib "$Bin/../libs";
use config;
my $USAGE = "perl decode.pl -list FILELIST -conv CONVERTTABLES -lab1 INPUTFOLDER [-h]";

main();

sub main {
	my $cl = config->new(\@ARGV);
	if ($cl->optionflag("-h")) {
		print $USAGE."\n";
		exit;
	}

	my $lab1;
	if ($cl->optionflag("-lab1")) {
		$lab1 = $cl->optionarg("-lab1");
	} else {
		die "no input folder specified. \n$USAGE.\n";
	}

	if (!-d "lab") {
		mkdir "lab";
		print STDERR "folder \"lab\" created\n";
	}
	if (!$cl->optionflag("-list") || !$cl->optionflag("-conv")) {
		die "error: the specified options are not valid/not all required options are specified.\n$USAGE\n";
	}
	my @list = readFile($cl->optionarg("-list"));		#the list must not contain file endings
	my @codelist = readFile($cl->optionarg("-conv"));
	foreach $f (@list) {
		my $infile = $f.'.lab1';
		my $outfile = $f.'.lab';
		$outfile =~ s/1$//;
		process($infile,\@codelist,$outfile, $lab1);
	}
}

sub process {
	my $file = shift;
	my $pCodelist = shift;
	my $outfile = shift;
	my $lab1 = shift;
	my @labels = readFile("$lab1/$file");		#files to process have to be in the folder "lab1"
	my %code = prepCode($pCodelist);
	my @res = convert(\@labels, \%code);
	open OUT, ">lab/$outfile" or die "could not create the output file $outfile. aborting\n";
	printOut(\@res, \*OUT);
	close(OUT);
}

#prints out the results
sub printOut {
	my $pRes = shift;
	my $handle = shift;
	
	foreach (@{$pRes}) {
		print $handle $_."\n";
	}
}


#converts coded HTK files into humanreadable htk files
sub convert {
	my $pLabels = shift;
	my $pCode = shift;
	my $l = @{$pLabels};
	my @res;
	for (my $i=0; $i<$l; $i++) {
		my @buffer = split(/ +/,$pLabels->[$i]);
		if ($buffer[2] eq "sp" || $buffer[2] eq "sil") {
			$res[$i] = $pLabels->[$i];
		}
		else {
			$buffer[2] =~ tr/xy/01/;
			if (!exists $pCode->{$buffer[2]}) {
				$buffer[2] =~ tr/01/xy/;
				die "key $buffer[2] not found in code tables\n";
			}
			$buffer[2] = $pCode->{$buffer[2]};
			$res[$i] = join(" ",@buffer);
		}
	}
	return(@res);
}

#reads code table and creates a code array; reads only the first two columns, all other columns will be ignored
sub prepCode {
	my $pCodelist = shift;
	my $l = @{$pCodelist};
	my %code;
	
	for (my $i=0; $i<$l; $i++) {
		my @buffer = split(/ +/,$pCodelist->[$i]);
		$code{$buffer[1]} = $buffer[0];
		#$code[$i][0] = $buffer[0];
		#$code[$i][1] = $buffer[1];
	}
	return(%code);
	#foreach (@{$pCodelist}) { print $_."\n";}
}

#reads files
sub readFile {
	my $file = shift;
	open IN, "$file" or die "could not open file $file to read\n";
	chomp(my @lines = <IN>);
	close(IN);
	return(@lines);
}

